package com.lagou.rpc.core;

import com.alibaba.fastjson.JSON;
import com.lagou.rpc.core.config.Provider;
import com.lagou.rpc.core.config.RpcConfig;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.net.InetAddress;
import java.util.Date;
import java.util.List;

@Component
public class ProviderRegister {

    @Autowired
    private  RpcZookeeperClient client;

    @Autowired
    private  RpcConfig rpcConfig;


    /**
     * 注册消息
     */
    @PostConstruct
    public void register() throws Exception {
        if (rpcConfig.getRegister() == null){
            return;
        }

        InetAddress address = InetAddress.getLocalHost();
        for (Provider provider : rpcConfig.getRegister()) {
            String url = address.getCanonicalHostName() + ":" + rpcConfig.getNettyPort();
            String nodeUrl =  client.getClient().create().creatingParentContainersIfNeeded()
                    .withMode(CreateMode.EPHEMERAL_SEQUENTIAL)
                    .forPath("/rpc/provider/"+provider.getName()+"/"+provider.getName()+"Service");
            ProviderNode providerNode = new ProviderNode();
            providerNode.setNodeUrl(nodeUrl);
            providerNode.setRequestTime(new Date());
            providerNode.setTime(Long.valueOf(0));
            providerNode.setProviderUrl(url);
            client.getClient().setData().forPath(nodeUrl,providerNode.toJson().getBytes());
            System.out.println("注册消息"+ providerNode.toJson());
        }


    }

}
